package domain;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.Writer;
import com.google.zxing.BarcodeFormat;

public class QRGenerator {
	
	private CharsetEncoder encoder;
	
	public QRGenerator(){
		setEncoder(Charset.forName("ISO-8859-1").newEncoder());
	}
	
	public CharsetEncoder getEncoder() {
		return encoder;
	}

	private void setEncoder(CharsetEncoder encoder) {
		this.encoder = encoder;
	}

	public BitMatrix generate(String input, int width, int height) throws DomainException{
		BitMatrix matrix = null;
		try {
			// Convert a string to ISO-8859-1 bytes in a ByteBuffer
			ByteBuffer bbuf = getEncoder().encode(CharBuffer.wrap(input));
			String data = new String(bbuf.array(), "ISO-8859-1");
			Writer writer = new QRCodeWriter();
			matrix = writer.encode(data,BarcodeFormat.QR_CODE, width, height);
		} catch (CharacterCodingException e) {
			throw new DomainException("kan input niet encoderen",e);
		} catch (UnsupportedEncodingException e) {
			throw new DomainException("kan geen iso string maken",e);
		} catch (com.google.zxing.WriterException e) {
			throw new DomainException("kan niet schrijven naar matrix",e);
		}
		return matrix;	
	}

}
